<template>
  <PageDialog
    :title="dialogInfo.title"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
    v-model:visible.sync="shows"
  >
    <PageFilter
      v-model:query.sync="filterInfo.query"
      :filter-list="filterInfo.list"
    >
    </PageFilter>
    <div class="resources-tree-auth">
      <el-tree
        ref="tree"
        v-model:data.sync="treeInfo.data"
        show-checkbox
        :props="treeInfo.defaultProps"
        :node-key="treeInfo.nodeKey"
        :default-expanded-keys="[-1]"
        :default-checked-keys="treeInfo.checked"
        :filter-node-method="filterNode"
        @check-change="handleSelectionChange"
        @check="getCurrentNode"
        @node-click="nodeClick"
      />
      <el-tree
        ref="cacheTree"
        :data="cacheTreeInfo.data"
        :props="cacheTreeInfo.defaultProps"
        :node-key="cacheTreeInfo.nodeKey"
        default-expand-all
      />
    </div>
  </PageDialog>
</template>

<script setup name="selectAssetClassIfyResource">
import PageDialog from '@/components/PageDialog/index'
import PageFilter from '@/components/PageFilter/index'
import { getClassifyTree } from '@/api/asset.js'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  showDialog: {
    type: Boolean,
  },
  // 查询已选权限的过滤参数
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  defaultList: {
    type: Array,
    default: function () {
      return []
    },
  },
})
const filterInfo = reactive({
  query: {
    keyword: '',
    ...props.query,
  },
  list: [
    {
      type: 'input',
      label: '名称/编码',
      value: 'keyword',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 弹窗相关
const dialogInfo = reactive({
  title: '选择资产分类资源',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', type: 'primary', event: save, show: true },
  ],
  width: '80%',
})
// 权限树
const treeInfo = reactive({
  data: [],
  nodeKey: 'id',
  checked: [],
  defaultProps: {
    children: 'children',
    label: function (data, node) {
      if (data.code) {
        return data.code + ' ' + data.name
      } else {
        return data.name
      }
    },
  },
})
const cacheTreeInfo = reactive({
  data: [],
  nodeKey: 'id',
  checked: [],
  defaultProps: {
    children: 'children',
    label: function (data, node) {
      if (data.code) {
        return data.code + ' ' + data.name
      } else {
        return data.name
      }
    },
  },
})

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})
onMounted(() => {
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    getTree()
  })
})
function getCurrentNode(data, data1) {
  //如果是底部节点,寻找父节点,并将父节点的子节点查看按钮设置上
  if (data.children === undefined && data1.halfCheckedNodes != null) {
    data1.halfCheckedNodes.forEach((val) => {
      if (
        val.id === data.parentId &&
        proxy.$refs.tree.getNode(val).indeterminate
      ) {
        val.children.forEach((item) => {
          if (item.code.endsWith(':list')) {
            proxy.$refs.tree.setChecked(item, true, true)
          }
        })
      }
    })
  }
}
function search() {
  proxy.$refs.tree.filter(filterInfo.query.keyword)
}
function getTree() {
  getClassifyTree(filterInfo.query).then((resp) => {
    if (resp && resp.success) {
      let data = [resp.data]
      treeInfo.data = data
      proxy.$nextTick(() => {
        if (props.defaultList[0] === 0) {
          proxy.$refs.tree.setCheckedKeys([treeInfo.data[0].id], false)
        } else {
          proxy.$refs.tree.setCheckedKeys(props.defaultList, false)
        }
      })
    }
  })
}

function save() {
  let data = []
  let getCheckedIds = proxy.$refs.tree.getCheckedKeys()

  if (getCheckedIds.includes(treeInfo.data[0].id)) {
    //全部勾选
    data.push({ name: '全部', id: 0 })
  } else {
    let treeData = proxy.$refs.tree.getCheckedNodes(false, false)
    data = treeData.map((item) => {
      return {
        id: item.id,
        name: item.name,
      }
    })
  }
  handleClose()
  emits('callback', data)
}
function getCheckedKeys(treeData, getCheckedIds) {
  if (getCheckedIds && getCheckedIds.length) {
    let data = treeData.filter((item) => {
      if (getCheckedIds.includes(item.id)) {
        return item
      } else {
        if (item.children && item.children.length) {
          item.children = getCheckedKeys(item.children, getCheckedIds)
          if (item.children && item.children.length) {
            return item
          }
        }
      }
    })
    return data
  } else {
    return []
  }
}
function handleSelectionChange(data, checked, indeterminate) {
  let getCheckedIds = proxy.$refs.tree.getCheckedKeys()
  let treeData = proxy.$fn.deepClone(treeInfo.data)
  cacheTreeInfo.data = getCheckedKeys(treeData, getCheckedIds)
}
function filterNode(value, data) {
  if (!value) return true
  return data.name.indexOf(value) !== -1
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
function nodeClick(obj, node) {
  //点击
  if (!node.childNodes.length) {
    proxy.$refs.tree.setChecked(obj, !node.checked, true)
  }
}
</script>
<style scoped lang="scss">
.resources-tree-auth {
  display: flex;
  justify-content: space-between;
  .el-tree {
    padding: 10px 0;
    height: 300px;
    overflow-y: auto;
    width: 48%;
    border: 1px solid #ecebeb;
  }
}
</style>
